﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Subfaculty.Common.Entities;
using ClosedXML.Excel;
using Subfaculty.WebApplication.ViewModels;
using Subfaculty.WebApplication.Translators;

namespace Subfaculty.WebApplication.Services
{
    public class ExportStudyLoadOfDepartmentToExcel : ExcelExport
    {
        private int MakeNotation(StudyLoadViewModel studyLoad, IXLWorksheet worksheet, int rowIndex)
        {
            WriteCell(worksheet.Range(rowIndex, 1, rowIndex, 5).Merge(), "Расчет учебной нагрузки по кафедре");
            WriteCell(worksheet.Range(rowIndex, 6, rowIndex, 26).Merge(), studyLoad.Department);
            return ++rowIndex;
        }

        public XLWorkbook ExportToExcel(StudyLoad studyLoad)
        {
            var workbook = new XLWorkbook();
            StudyLoadViewModel studyLoadViewModel = new StudyLoadTranslator().Translate(studyLoad);

            var worksheet = workbook.Worksheets.Add(studyLoadViewModel.Department);
            int currentRowIndex = MakeNotation(studyLoadViewModel, worksheet, 1);

            currentRowIndex = MakeHeaders(worksheet, currentRowIndex);

            var semesterGroups = from sgroup in
                                     (from item in studyLoadViewModel.StudyLoadItems
                                      group item by item.Semester)
                                 orderby sgroup.Key ascending
                                 select sgroup;

            foreach (var group in semesterGroups)
            {
                currentRowIndex = ExportSemester(worksheet, currentRowIndex, group.AsEnumerable<StudyLoadItemViewModel>(), group.Key);
            }

            //workbook.SaveAs("DEP.xlsx");//test
            return workbook;
        }
    }

}
